package com.wan37.logic.db;

import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @author : luoyong
 * @date : 2020-07-17 10:22
 **/
@Component
public class Work implements Runnable {

    private final Executor asynDBUtilExecutor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1000), new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("异步线程池线程：");
            return thread;
        }
    });

    private final LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    @Override
    public void run() {
        while (true) {
            Runnable runnable = null;
            try {
                runnable = queue.poll(500, TimeUnit.MILLISECONDS);
                if (runnable == null) {
                    continue;
                }
                asynDBUtilExecutor.execute(runnable);
            } catch (Exception e) {
                asynDBUtilExecutor.execute(runnable);
            }
        }
    }

    public void addTask(Runnable runnable) {
        if (runnable != null) {
            queue.offer(runnable);
        }
    }
}
